<?php


namespace App\Middleware;


use App\Model\User;
use Kiri;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Kiri\Redis\Redis;

/**
 * Class CheckAuthMiddleware
 * @package App\Http\Middleware
 */
class OAuthMiddleware implements MiddlewareInterface
{


	/**
	 * @param ServerRequestInterface $request
	 * @param RequestHandlerInterface $handler
	 * @return ResponseInterface
	 * @throws
	 */
	public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
	{
		/** @var Kiri\Router\Response $response */
		$response = Kiri::getDi()->get(ResponseInterface::class);
		$header = $request->getHeaderLine('x-token');
		if (empty($header)) {
			return $response->write('Auth error', 401);
		}

		$redis = Kiri::getDi()->get(Redis::class);

		/** @var User $admin */
		$admin = User::query()->where(['id' => (int)$redis->get($header)])->first();
		if (is_null($admin)) {
			return $response->write('Auth error', 401);
		}

		return $handler->handle($request->withAuthority($admin));
	}


}
